// 引入文件操作相关模块
const fs = require('fs')
const path = require('path')

// 图片上传
exports.imgUpload = function(req, res) {
	let imgName = req.body.name // 上传的自定义文件名
	let imgInfo = req.files[0] // 上传的文件信息

	var des_file = "./data/" + req.body.name; // 保存图片的地址
	fs.readFile(imgInfo.path, function(err, data) {
		fs.writeFile(des_file, data, function(err) {
			if (err) {
				console.log(err);
			} else {
				let response = {
					message: 'File uploaded successfully',
					filename: imgName
				};
				console.log(response);
				res.send({
					info: `${imgName}图片上传成功`
				});
				fs.unlinkSync(req.files[0].path) // 删除multer默认保存图片
			}
		});
	});
}

// 图片删除
exports.imgDelete = function(req, res) {
	fs.unlinkSync(path.join(__dirname, '..', 'data', req.body.imgName))
	res.send({info:`${req.body.imgName}图片删除成功`})
}
